use axum::Json;
use serde_json::Value;
use sea_orm::EntityTrait;
use crate::{code, query};

use super::del::{many, one};

// 删除单个
pub async fn by_id_del_file<E:EntityTrait>(entity:E, body:&Value, file:Vec<&str>, mongo:bool) -> Result<Json<Value>, Json<Value>>{
    one(entity, "id", Some(query::u32(body, "id")?), None, Some(file), mongo).await
}
pub async fn by_id<E:EntityTrait>(entity:E, body:&Value) -> Result<Json<Value>, Json<Value>>{
    by_id_del_file(entity, body, Vec::new(), false).await
}
// 删除多个
pub async fn by_ids_del_file<E:EntityTrait>(entity:E, body:&Value, file:Vec<&str>, mongo:bool) -> Result<Json<Value>, Json<Value>>{
    let ids = query::vec_u32_json(body, "id")?;
    if ids.len() == 1 {
        let id = ids[0];
        one(entity, "id", Some(id), None, Some(file), mongo).await
    }else{
        many(entity, "id", Some(ids) , None, Some(file), mongo).await
    }
}
pub async fn by_ids<E:EntityTrait>(entity:E, body:&Value) -> Result<Json<Value>, Json<Value>>{
    by_ids_del_file(entity, body, Vec::new(), false).await
}
// 自动字段
pub async fn by_field_auto_del_file<E:EntityTrait>(entity:E, body:&Value, field:&str, file:Vec<&str>, mongo:bool) -> Result<Json<Value>, Json<Value>>{
    if let Some(f) = body[field].as_i64() {
        one(entity, field, Some(f as u32), None, Some(file), mongo).await
    }else{
        if let Some(f) = query::vec_u32_json_op(&body, field)? {
            many(entity, field, Some(f), None, Some(file), mongo).await
        }else{
            Err(code::err_("传递参数不正确"))
        }
    }
}
pub async fn by_field_auto<E:EntityTrait>(entity:E, body:&Value, field:&str,) -> Result<Json<Value>, Json<Value>>{
    by_field_auto_del_file(entity, body, field, Vec::new(), false).await
}
pub async fn by_id_auto_del_file<E:EntityTrait>(entity:E, body:&Value, file:Vec<&str>, mongo:bool) -> Result<Json<Value>, Json<Value>>{ by_field_auto_del_file(entity, body, "id", file, mongo).await }
pub async fn by_id_auto<E:EntityTrait>(entity:E, body:&Value) -> Result<Json<Value>, Json<Value>>{ by_id_auto_del_file(entity, body, Vec::new(), false).await }